package com.example.tourstor;

import android.app.ListActivity;
import android.content.Intent;
import android.graphics.drawable.PaintDrawable;
import android.os.Handler;
import android.os.Message;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.example.tourstor.adapter.FirstClassAdapter;
import com.example.tourstor.adapter.SecondClassAdapter;
import com.example.tourstor.database.MerchantItem;
import com.example.tourstor.model.FirstClassItem;
import com.example.tourstor.model.SecondClassItem;
import com.example.tourstor.utils.ScreenUtils;
import com.example.tourstor.MerchantActivity;
import com.example.tourstor.Merchant_search;
import com.example.tourstor.R;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class MerchantFragment extends Fragment {

    private static final String TAG = "MerchantFragment";
    private LinearLayout search;
    private Intent intent;

    private TextView classBtn;
    private TextView placeBtn;
    private TextView sortBtn;

//    private TextView mainTab1TV;
    /**
     * 左侧一级分类的数据
     */
    private List<FirstClassItem> firstList;
    /**
     * 右侧二级分类的数据
     */
    private List<SecondClassItem> secondList;

    /**
     * 使用PopupWindow显示一级分类和二级分类
     */
    private PopupWindow popupWindow;

    /**
     * 左侧和右侧两个ListView
     */
    private ListView leftLV, rightLV;
    //弹出PopupWindow时背景变暗
    private View darkView;

    //弹出PopupWindow时，背景变暗的动画
    private Animation animIn, animOut;

    Thread thread;
    private ListView listView;
    private ListAdapter listAdapter;
    private Handler handler;
    //    private DBManager dbManager = DBManager.createInstance();
    private MerchantItem merchantItem = new MerchantItem();
    private ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.frame_merchant, container);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        search = getActivity().findViewById(R.id.btn_to_search);
        classBtn = getActivity().findViewById(R.id.merchant_classification);
        placeBtn = getActivity().findViewById(R.id.merchant_place);
        sortBtn = getActivity().findViewById(R.id.merchant_sort);

        darkView = getActivity().findViewById(R.id.merchant_darkview);
        animIn = AnimationUtils.loadAnimation(getActivity(), R.anim.fade_in_anim);
        animOut = AnimationUtils.loadAnimation(getActivity(), R.anim.fade_out_anim);

        listView = getActivity().findViewById(R.id.merchant_list);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                TextView merchantNo = view.findViewById(R.id.merchantItem_no);
                int n = Integer.valueOf(merchantNo.getText().toString());
                intent = new Intent(getActivity(), MerchantActivity.class);
                intent.putExtra("Mno", n);
                Log.i(TAG, "onItemClick: Mno = " + n);
                startActivity(intent);
            }
        });


        search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                intent = new Intent(getActivity(), Merchant_search.class);
                startActivity(intent);
            }
        });

        classBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i(TAG, "onClick: classBtn");
                initClassData();
                initPopup(classBtn);
                tab1OnClick();
            }
        });


        placeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i(TAG, "onClick: placeBtn");
                initPlaceData();
                initPopup(placeBtn);
                tab1OnClick();
            }
        });


        sortBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i(TAG, "onClick: sortBtn");
                initSortData();
                initPopup(sortBtn);
                tab1OnClick();
            }
        });

        handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if(msg.what == 1){

                    listAdapter = new SimpleAdapter(getActivity(), list, R.layout.item_merchant,
                            new String[]{"Mno", "Mname", "Mscore", "Mclass", "Mplace"},
                            new int[]{R.id.merchantItem_no, R.id.merchantItem_name, R.id.merchantItem_score, R.id.merchantItem_class, R.id.merchantItem_place});
                    listView.setAdapter(listAdapter);
                }



            }
        };

    }

    @Override
    public void onStart() {
        super.onStart();
        initList();
    }

    private void initList(){

        new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (this){
                    list = merchantItem.getMerchantInfo("select * from merchant");
                    Message msg = handler.obtainMessage(1);
                    msg.what = 1;
                    handler.sendMessage(msg);
                }
            }
        }).start();


    }





    private void initClassData() {
        firstList = new ArrayList<FirstClassItem>();

        ArrayList<SecondClassItem> secondList1 = new ArrayList<SecondClassItem>();
        secondList1.add(new SecondClassItem(101, "自助餐"));
        secondList1.add(new SecondClassItem(102, "西餐"));
        secondList1.add(new SecondClassItem(103, "川菜"));
        firstList.add(new FirstClassItem(1, "美食", secondList1));

        ArrayList<SecondClassItem> secondList3 = new ArrayList<SecondClassItem>();
        secondList3.add(new SecondClassItem(201, "南开区"));
        secondList3.add(new SecondClassItem(202, "和平区"));
        secondList3.add(new SecondClassItem(203, "河西区"));
        secondList3.add(new SecondClassItem(204, "河东区"));
        secondList3.add(new SecondClassItem(205, "滨海新区"));
        firstList.add(new FirstClassItem(2, "电影", secondList3));

        firstList.add(new FirstClassItem(3, "手机", new ArrayList<SecondClassItem>()));

        firstList.add(new FirstClassItem(4, "娱乐", null));

    }

    private void initPlaceData() {
        firstList = new ArrayList<FirstClassItem>();

        ArrayList<SecondClassItem> secondList2 = new ArrayList<SecondClassItem>();
        secondList2.add(new SecondClassItem(101, "天津"));
        secondList2.add(new SecondClassItem(102, "北京"));
        secondList2.add(new SecondClassItem(103, "秦皇岛"));
        secondList2.add(new SecondClassItem(104, "沈阳"));
        secondList2.add(new SecondClassItem(105, "大连"));
        secondList2.add(new SecondClassItem(106, "哈尔滨"));
        secondList2.add(new SecondClassItem(107, "锦州"));
        secondList2.add(new SecondClassItem(108, "上海"));
        secondList2.add(new SecondClassItem(109, "杭州"));
        secondList2.add(new SecondClassItem(110, "南京"));
        secondList2.add(new SecondClassItem(111, "嘉兴"));
        secondList2.add(new SecondClassItem(112, "苏州"));
        firstList.add(new FirstClassItem(1, "旅游", secondList2));

        ArrayList<SecondClassItem> secondList3 = new ArrayList<SecondClassItem>();
        secondList3.add(new SecondClassItem(201, "南开区"));
        secondList3.add(new SecondClassItem(202, "和平区"));
        secondList3.add(new SecondClassItem(203, "河西区"));
        secondList3.add(new SecondClassItem(204, "河东区"));
        secondList3.add(new SecondClassItem(205, "滨海新区"));
        firstList.add(new FirstClassItem(2, "电影", secondList3));

    }

    private void initSortData() {
        firstList = new ArrayList<FirstClassItem>();

        firstList.add(new FirstClassItem(1, "离我最近", new ArrayList<SecondClassItem>()));
        firstList.add(new FirstClassItem(2, "好评优先", new ArrayList<SecondClassItem>()));
        firstList.add(new FirstClassItem(3, "销量优先", new ArrayList<SecondClassItem>()));

    }

    private void initPopup(final TextView textView) {
        popupWindow = new PopupWindow(getActivity());
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.popup_layout, null);
        leftLV = (ListView) view.findViewById(R.id.pop_listview_left);
        rightLV = (ListView) view.findViewById(R.id.pop_listview_right);

        popupWindow.setContentView(view);
        popupWindow.setBackgroundDrawable(new PaintDrawable());
        popupWindow.setFocusable(true);

        popupWindow.setHeight(ScreenUtils.getScreenH(getActivity()) * 2 / 3);
        popupWindow.setWidth(ScreenUtils.getScreenW(getActivity()));

        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                darkView.startAnimation(animOut);
                darkView.setVisibility(View.GONE);

                leftLV.setSelection(0);
                rightLV.setSelection(0);
            }
        });


        //为了方便扩展，这里的两个ListView均使用BaseAdapter.如果分类名称只显示一个字符串，建议改为ArrayAdapter.
        //加载一级分类
        final FirstClassAdapter firstAdapter = new FirstClassAdapter(getActivity(), firstList);
        leftLV.setAdapter(firstAdapter);

        //加载左侧第一行对应右侧二级分类
        secondList = new ArrayList<SecondClassItem>();
        secondList.addAll(firstList.get(0).getSecondList());
        final SecondClassAdapter secondAdapter = new SecondClassAdapter(getActivity(), secondList);
        rightLV.setAdapter(secondAdapter);

        //左侧ListView点击事件
        leftLV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //二级数据
                List<SecondClassItem> list2 = firstList.get(position).getSecondList();
                //如果没有二级类，则直接跳转
                if (list2 == null || list2.size() == 0) {
                    popupWindow.dismiss();

                    int firstId = firstList.get(position).getId();
                    String selectedName = firstList.get(position).getName();
                    handleResult(firstId, -1, selectedName, textView);
                    return;
                }

                FirstClassAdapter adapter = (FirstClassAdapter) (parent.getAdapter());
                //如果上次点击的就是这一个item，则不进行任何操作
                if (adapter.getSelectedPosition() == position) {
                    return;
                }

                //根据左侧一级分类选中情况，更新背景色
                adapter.setSelectedPosition(position);
                adapter.notifyDataSetChanged();

                //显示右侧二级分类
                updateSecondListView(list2, secondAdapter);
            }
        });

        //右侧ListView点击事件
        rightLV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //关闭popupWindow，显示用户选择的分类
                popupWindow.dismiss();

                int firstPosition = firstAdapter.getSelectedPosition();
                int firstId = firstList.get(firstPosition).getId();
                int secondId = firstList.get(firstPosition).getSecondList().get(position).getId();
                String selectedName = firstList.get(firstPosition).getSecondList().get(position)
                        .getName();
                handleResult(firstId, secondId, selectedName, textView);
            }
        });
    }

    //顶部第一个标签的点击事件
    private void tab1OnClick() {
        if (popupWindow.isShowing()) {
            popupWindow.dismiss();
        } else {
            popupWindow.showAsDropDown(getActivity().findViewById(R.id.main_div_line));
            popupWindow.setAnimationStyle(-1);
            //背景变暗
            darkView.startAnimation(animIn);
            darkView.setVisibility(View.VISIBLE);
        }
    }

    //刷新右侧ListView
    private void updateSecondListView(List<SecondClassItem> list2,
                                      SecondClassAdapter secondAdapter) {
        secondList.clear();
        secondList.addAll(list2);
        secondAdapter.notifyDataSetChanged();
    }

    //处理点击结果
    private void handleResult(int firstId, int secondId, String selectedName, TextView textView) {
        String text = "first id:" + firstId + ",second id:" + secondId;
        Toast.makeText(getActivity(), text, Toast.LENGTH_SHORT).show();

        textView.setText(selectedName);
    }


}
